﻿using System;
using System.Buffers;
using SuperSocket.ProtoBase;

namespace Demo005 
{
    
    
    /**
     *
     *
     *
     *
     * 
     *  0 1      2   3    4  5   6        7     8 9     10 11
     *  事务标识2+协议标识2 +长度2 +单元标识1 +功能码1 +地址2 +寄存器2
     *
     *
     * 00 02 00 00 00 06 01 03 00 00 00 02
     00 02 00 00 00 06 01 03 00 00 00 02
     */
    public class ModbusPipelineFilter:FixedHeaderPipelineFilter<ModbusPackageInfo>
    {



         
        /// <summary>
        /// 包头字节
        /// </summary>
        /// <param name="headerSize"></param>
         
        public ModbusPipelineFilter() : base(6)
        {
            
        }


        //从数据包的夈部返回包体的大小。
        protected override int GetBodyLengthFromHeader(ref ReadOnlySequence<byte> buffer)
        {
 
                
                var reader = new SequenceReader<byte>(buffer);

                  
                
                
                reader.Advance(4); 

                reader.TryReadBigEndian(out short len);
    
                
                //判断是不是tcp协议 byte为00 00
 
                
                
                Console.WriteLine($"GetBodyLengthFromHeader:len {len}   {string.Join(" ",buffer.ToArray()) }");

                
                //如果协议不对。
                
                if (len > 125)
                {
                    throw new Exception("len >125");
                }
                 
                return len;
           
           
 
        }


        /// <summary>
        /// 数据包解析成对象
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        protected override ModbusPackageInfo DecodePackage(ref ReadOnlySequence<byte> buffer)
        {

            
                
            
                var package = new ModbusPackageInfo();

                var reader = new SequenceReader<byte>(buffer);
                
                
                
              
                reader.Advance(5);
                
                reader.TryRead(out byte len);
                
                Console.WriteLine($" len:{len.ToString()}");

                package.Len = len;
                
                reader.Advance(1);
                
            
             

                reader.TryRead(out byte key);

                package.Key = key;

                 
                Console.WriteLine($" key:{key.ToString()}");
                
                

               //长度后面 
               var reader_body = new SequenceReader<byte>(buffer).Sequence.Slice(6);
                
               package.Body = reader_body.ToArray();

               Console.WriteLine($"reader_body--{string.Join(" ", reader_body.ToArray())}");
                return package;

                
           


        }

    }


 
}